/**
 * 消息推荐的Service
 */
package net.youpo.Market.Service;

import java.io.File;
import java.lang.ref.SoftReference;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import net.youpo.Market.R;
import net.youpo.Market.Bean.AppInfoBean;
import net.youpo.Market.Bean.MessageBean;
import net.youpo.Market.Net.HttpConnection;
import net.youpo.Market.UI.AppInfo.MessageAppInfoActivity;
import net.youpo.Market.Util.ConstantsTable;
import net.youpo.Market.Util.DeviceInfo;
import net.youpo.Market.Util.GlobalVariables;
import net.youpo.Market.Util.Tools;
import net.youpo.Market.db.MarketDatabase;
import net.youpo.Market.db.MessageTable;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;

public class MessageService extends Service {
    private final String REQS_CONFIG = "Push/";
    private boolean running_flag = false;
    private HttpConnection mHC = new HttpConnection();
    private NotificationManager mNotificationManager;
    private ArrayList<MessageBean> mMessageList = new ArrayList<MessageBean>();
    DateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        Log.v("TrafficService", "startCommand");

        flags = START_STICKY;
        return super.onStartCommand(intent, flags, startId);
        // return START_REDELIVER_INTENT;
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        if (running_flag) {
            return;
        }
        running_flag = true;
        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        setForeground(true);

        // 1.从服务器上获取消息
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (running_flag) {
                    // Log.e("H3c", "service is running");
                    getMessageFromServer();
                    // 2.查询所有的消息，清除已经过期的消息
                    getAllMessage();
                    try {
                        Thread.sleep(GlobalVariables.DATA_REFRESH_TIME);
                        // Thread.sleep(10000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // running_flag = false;
        Intent localIntent = new Intent();
        localIntent.setClass(this, MessageService.class); // 销毁时重新启动Service
        this.startService(localIntent);
    }

    /**
     * 从服务器上获取推送消息
     */
    private void getMessageFromServer() {
        Date date = null;
        String resultJson = mHC.requestService(REQS_CONFIG, new String[] {
                ConstantsTable.KEY_VC, ConstantsTable.NOW_VERSION,
                ConstantsTable.KEY_IMEI, ConstantsTable.IMEI });

        // 2.解析信息
        try {
            JSONTokener jsonParser = new JSONTokener(resultJson);
            JSONObject person = (JSONObject) jsonParser.nextValue();

            JSONArray jsonArr = person.getJSONArray("pushs");
            int length = jsonArr.length();
            for (int i = 0; i < length; i++) {// 遍历JSONArray
                JSONObject oj = jsonArr.getJSONObject(i);
                String id = oj.getString("id");
                String time = oj.getString("ts");
                JSONObject oj2 = oj.getJSONObject("app");
                String name = oj2.getString("an");
                String icon = oj2.getString("icon");
                String dc = oj2.getString("dc");
                String au = oj2.getString("au");
                String pn = oj2.getString("pn");
                String ver = oj2.getString("ver");
                String vc = oj2.getString("vc");
                String sz = oj2.getString("sz");
                String desc = oj2.getString("desc");
                String cat = oj2.getString("cat");
                String dl = oj2.getString("dl");
                JSONArray oj3 = oj2.getJSONArray("st");
                JSONObject oj4 = oj3.getJSONObject(0);
                String timg = oj4.getString("timg");

                // String转Date
                try {
                    date = dateformat.parse(time);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                Date nowDate = new Date();
                long dateTime = date.getTime();
                long nowTime = nowDate.getTime();
                if (dateTime < nowTime) {// 如果消息已经过期就放弃
                    continue;
                }
                // 1.从已有的消息数据库中查询消息是否存在
                boolean oldMessageFlag = false;
                SQLiteDatabase marketDB = MarketDatabase.getMarketDB();
                // 查询表中的数据
                Cursor cursor = marketDB.query(MessageTable.TABLE_NAME, null,
                        MessageTable.MESSAGEID + "=?", new String[] { id },
                        null, null, null);
                // 获取列的索引
                // int columnId = cursor.getColumnIndex(MessageTable.ID);
                int messageInt = cursor.getColumnIndex(MessageTable.MESSAGEID);
                // int appInt = cursor.getColumnIndex(MessageTable.APPID);
                // int timeInt = cursor.getColumnIndex(MessageTable.TIME);
                // int appName = cursor.getColumnIndex(MessageTable.NAME);
                // int iconi = cursor.getColumnIndex(MessageTable.ICON);
                // int dci = cursor.getColumnIndex(MessageTable.DOWNLOAD_COUNT);
                // int aui = cursor.getColumnIndex(MessageTable.AUTHOR);
                // int pni = cursor.getColumnIndex(MessageTable.PUCKAGE_NAME);
                // int veri = cursor.getColumnIndex(MessageTable.VERSION_NAME);
                // int vci = cursor.getColumnIndex(MessageTable.VERSION_CODE);
                // int szi = cursor.getColumnIndex(MessageTable.SIZE);
                // int desci = cursor.getColumnIndex(MessageTable.DESE);
                // int cati = cursor.getColumnIndex(MessageTable.CAT);
                // int dli = cursor.getColumnIndex(MessageTable.DOWNLOAD_LINE);
                // int timgi = cursor.getColumnIndex(MessageTable.IMAGE_URL);
                for (cursor.moveToFirst(); !(cursor.isAfterLast()); cursor
                        .moveToNext()) {
                    MessageBean mb = new MessageBean();
                    // mb.ID = cursor.getString(columnId);
                    mb.MESSAGE_ID = cursor.getString(messageInt);
                    // mb.APP_ID = cursor.getString(appInt);
                    // mb.TIME = cursor.getString(timeInt);
                    // mb.APP_NAME = cursor.getString(appName);
                    // mb.APP_ICON = cursor.getString(iconi);
                    // mb.DOWNLOAD_COUNT = cursor.getString(dci);
                    // mb.AUTHOR = cursor.getString(aui);
                    // mb.PUCKAGE_NAME = cursor.getString(pni);
                    // mb.VERSION_NAME = cursor.getString(veri);
                    // mb.VERSION_CODE = cursor.getString(vci);
                    // mb.SIZE = cursor.getString(szi);
                    // mb.DESE = cursor.getString(desci);
                    // mb.CAT = cursor.getString(cati);
                    // mb.DOWNLOAD_LINE = cursor.getString(dli);
                    // mb.IMAGE_URL = cursor.getString(timgi);
                    if (id.equals(mb.MESSAGE_ID)) {
                        oldMessageFlag = true;
                    }
                }
                cursor.close();// 关闭结果集
                // TODO
                // 2.插入消息进消息数据库
                if (!oldMessageFlag) {
                    JSONObject subJson = oj.getJSONObject("app");
                    String appId = subJson.getString("id");

                    ContentValues tcv = new ContentValues();
                    tcv.put(MessageTable.MESSAGEID, id);
                    tcv.put(MessageTable.APPID, appId);
                    tcv.put(MessageTable.TIME, time);
                    tcv.put(MessageTable.NAME, name);
                    tcv.put(MessageTable.ICON, icon);
                    tcv.put(MessageTable.DOWNLOAD_COUNT, dc);
                    tcv.put(MessageTable.AUTHOR, au);
                    tcv.put(MessageTable.PUCKAGE_NAME, pn);
                    tcv.put(MessageTable.VERSION_NAME, ver);
                    tcv.put(MessageTable.VERSION_CODE, vc);
                    tcv.put(MessageTable.SIZE, sz);
                    tcv.put(MessageTable.DESE, desc);
                    tcv.put(MessageTable.CAT, cat);
                    tcv.put(MessageTable.DOWNLOAD_LINE, dl);
                    tcv.put(MessageTable.IMAGE_URL, timg);
                    marketDB.insert(MessageTable.TABLE_NAME, null, tcv);

                    // if (dateTime < (nowTime + 86400000)) {//
                    // 如果这个消息在24小时以内就实行预通知
                    // Timer timer = new Timer();
                    // timer.schedule(new setNotification("你有一条新消息", "七魄市场推荐",
                    // "点击查看推荐信息", appId, id), date);
                    // }
                } else {
                    continue;
                }
            }
        } catch (JSONException e) {
            Log.d(ConstantsTable.LOG_TAG, "messageService json error!");
            e.printStackTrace();
        }
    }

    /**
     * 获取所有的消息
     */
    private void getAllMessage() {
        mMessageList.clear();
        SQLiteDatabase marketDB = MarketDatabase.getMarketDB();
        // 查询表中的数据
        Cursor cursor = marketDB.query(MessageTable.TABLE_NAME, null, null,
                null, null, null, null);

        // 获取列的索引
        int columnId = cursor.getColumnIndex(MessageTable.ID);
        int messageInt = cursor.getColumnIndex(MessageTable.MESSAGEID);
        int appInt = cursor.getColumnIndex(MessageTable.APPID);
        int timeInt = cursor.getColumnIndex(MessageTable.TIME);
        int appName = cursor.getColumnIndex(MessageTable.NAME);
        int appIcon = cursor.getColumnIndex(MessageTable.ICON);
        int appPack = cursor.getColumnIndex(MessageTable.PUCKAGE_NAME);

        for (cursor.moveToFirst(); !(cursor.isAfterLast()); cursor.moveToNext()) {
            MessageBean mb = new MessageBean();
            mb.ID = cursor.getString(columnId);
            mb.MESSAGE_ID = cursor.getString(messageInt);
            mb.APP_ID = cursor.getString(appInt);
            mb.TIME = cursor.getString(timeInt);
            mb.APP_NAME = cursor.getString(appName);
            mb.APP_ICON = cursor.getString(appIcon);
            mb.PUCKAGE_NAME = cursor.getString(appPack);
            if (mb.ICON_BMP == null) {
                File file = new File(ConstantsTable.CACHE_PATH + "/"
                        + mb.APP_ID);
                Bitmap bmp = null;
                if (file.exists()) {// 如果有缓存文件
                    bmp = Tools.getBitmapFromCache(ConstantsTable.CACHE_PATH
                            + "/" + mb.APP_ID);
                } else {// 没有缓存就从网络获取
                    HttpConnection hc = new HttpConnection();
                    bmp = hc.getNetworkBitmap(mb.APP_ICON);

                    Tools.saveBmpToSd(bmp, mb.APP_ID);// 保存至缓存
                }
                mb.ICON_BMP = new SoftReference<Bitmap>(bmp);
            }
            mMessageList.add(mb);
        }
        cursor.close();// 关闭结果集

        for (MessageBean mb : mMessageList) {
            Date date = null;
            try {
                date = dateformat.parse(mb.TIME);
            } catch (ParseException e) {
                e.printStackTrace();
            }

            Date nowDate = new Date();
            long dateTime = date.getTime();
            long nowTime = nowDate.getTime();
            if (dateTime < nowTime) {// 如果消息已经过期就删除
                marketDB.delete(MessageTable.TABLE_NAME, MessageTable.MESSAGEID
                        + " = ?", new String[] { mb.MESSAGE_ID });
            } else if (dateTime < (nowTime + 86400000)) {// 如果这个消息在24小时以内就实行预通知
                boolean flag = true;
                if (GlobalVariables.ALL_INSTALL_APP.size() == 0) {
                    GlobalVariables.ALL_INSTALL_APP = DeviceInfo
                            .getInstallAppInfo();
                }

                for (AppInfoBean aib : GlobalVariables.ALL_INSTALL_APP) {
                    if (aib.APP_PACK.equals(mb.PUCKAGE_NAME)) {
                        flag = false;
                        break;
                    }
                }
                if (flag) {// 如果安装了这个程序就不弹出推送
                    if (GlobalVariables.MESSAGE_MAP.get(mb.MESSAGE_ID) == null) {// 如果这个消息没有创建
                        Random random = new Random();
                        int tempId = random.nextInt();
                        GlobalVariables.MESSAGE_MAP.put(mb.MESSAGE_ID, tempId);
                        Timer timer = new Timer();
                        timer.schedule(new setNotification("你有一条新消息",
                                mb.APP_NAME, "点击查看推荐信息", mb.APP_ID,
                                mb.MESSAGE_ID, tempId, mb), date);
                        Log.e("H3c", mb.APP_NAME + "M");
                    } else {
                        Log.d("H3c", mb.APP_NAME + "M");
                    }
                } else {
                    Log.i("H3c", mb.APP_NAME + "M");
                }
            }
        }

    }

    public class setNotification extends TimerTask {
        String tickrText;
        String Notititle;
        String Noticontent;
        String AppId;
        String MessageId;
        MessageBean AppIcon;
        int NotifyId;

        public setNotification(String tickrText, String Notititle,
                String Noticontent, String AppId, String MessageId,
                int notificationId, MessageBean AppIcon) {
            this.tickrText = tickrText;
            this.Notititle = Notititle;
            this.Noticontent = Noticontent;
            this.AppId = AppId;
            this.MessageId = MessageId;
            this.NotifyId = notificationId;
            this.AppIcon = AppIcon;
        }

        @Override
        public void run() {
            Notification(tickrText, Notititle, Noticontent, AppId, MessageId,
                    NotifyId, AppIcon);
        }
    }

    public void Notification(String tickrText, String Notititle,
            String Noticontent, String AppId, String MessageId,
            int NotificationId, MessageBean AppIcon) {
        int tempId = NotificationId;
        Intent intent = new Intent(MessageService.this,
                MessageAppInfoActivity.class);
        intent.putExtra(ConstantsTable.KEY_APPID, AppId);
        intent.putExtra(ConstantsTable.IS_RECOMMEND, true);
        intent.putExtra(ConstantsTable.RECOMMEND_ID, MessageId);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Notification notification = new Notification(R.drawable.message,
                tickrText, System.currentTimeMillis());
        PendingIntent contentIntent = PendingIntent.getActivity(this, tempId,
                intent, 0);
        notification.setLatestEventInfo(this, Notititle, Noticontent,
                contentIntent);
        RemoteViews rv = new RemoteViews(getPackageName(),
                R.layout.notification);
        notification.contentView = rv;
        rv.setTextViewText(R.id.notification_tv, Notititle);
        if (AppIcon != null && AppIcon.ICON_BMP != null
                && AppIcon.ICON_BMP.get() != null) {
            rv.setImageViewBitmap(R.id.notification_icon,
                    AppIcon.ICON_BMP.get());
        } else if (AppIcon != null && AppIcon.ICON_BMP != null) {
            if (AppIcon.ICON_BMP.get() == null) {
                File file = new File(ConstantsTable.CACHE_PATH + "/"
                        + AppIcon.APP_ID);
                Bitmap bmp = null;
                if (file.exists()) {// 如果有缓存文件
                    bmp = Tools.getBitmapFromCache(ConstantsTable.CACHE_PATH
                            + "/" + AppIcon.APP_ID);
                } else {// 没有缓存就从网络获取
                    HttpConnection hc = new HttpConnection();
                    bmp = hc.getNetworkBitmap(AppIcon.APP_ICON);

                    Tools.saveBmpToSd(bmp, AppIcon.APP_ID);// 保存至缓存
                }
                AppIcon.ICON_BMP = new SoftReference<Bitmap>(bmp);
                rv.setImageViewBitmap(R.id.notification_icon,
                        AppIcon.ICON_BMP.get());
            }
        } else if (AppIcon != null) {
            if (AppIcon.ICON_BMP == null) {
                File file = new File(ConstantsTable.CACHE_PATH + "/"
                        + AppIcon.APP_ID);
                Bitmap bmp = null;
                if (file.exists()) {// 如果有缓存文件
                    bmp = Tools.getBitmapFromCache(ConstantsTable.CACHE_PATH
                            + "/" + AppIcon.APP_ID);
                } else {// 没有缓存就从网络获取
                    HttpConnection hc = new HttpConnection();
                    bmp = hc.getNetworkBitmap(AppIcon.APP_ICON);

                    Tools.saveBmpToSd(bmp, AppIcon.APP_ID);// 保存至缓存
                }
                AppIcon.ICON_BMP = new SoftReference<Bitmap>(bmp);
                rv.setImageViewBitmap(R.id.notification_icon,
                        AppIcon.ICON_BMP.get());
            }
        }else{
        }
        notification.defaults = Notification.DEFAULT_ALL;
        mNotificationManager.notify(tempId, notification);
    }
}
